﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDO.DataPersistence.Core
{

    public class EnumerationDictionary<T, U> where U : PersistableDataObject, new()
    {

        static public Dictionary<T, U> Create(PersistableDataObjectList<U> list, string keyPropertyName)
        {
            Dictionary<T, U> lookupDictionary = null;

            lookupDictionary = new Dictionary<T, U>();

            // Add all items as defined in Lookup enum into dictionary.

            // Use the enum type as authoritative source of enumerated values to ensure congruence
            // between database and SPEDGen generated code.  By working from the enum defined values
            // we will guarantee that the database at least supports all the currently defined values.
            // Thus the database may contain values in addition to those defined in the enum,
            // which allows for backward compatibility.

            foreach (string key in Enum.GetNames(typeof(T)))
            {
                U i = PersistableDataObject.GetListItem<U>(list, keyPropertyName, key, true);

                // CX TEMP
                if (null == i)
                {
                    continue; // CX TEMP
                    //throw new InvalidOperationException("Lookup value for enumeration key name of " + key + " not found in database.");
                }

                i.IsImmutable = true; // enumeration objects are immutable.

                lookupDictionary.Add((T)Enum.Parse(typeof(T), key), i);
            }
            return lookupDictionary;
        }

        static public T GetEnumerationValue(PersistableDataObject pdo, string lookupKey, out bool isValid)
        {
            isValid = false;
            T value = default(T);
            try
            {
                if (lookupKey != null)
                {
                    value = (T)Enum.Parse(typeof(T), lookupKey, false);
                    isValid = true;
                }
            }
            catch (ArgumentException)
            {
                value = default(T);
            }

            return value;
        }
    }
}
